package com.xjprojectc.base.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.util.FileCopyUtils;

import com.opensymphony.xwork2.ActionContext;
import com.tech.framework.action.BaseAction;
import com.xjprojectc.business.pojo.T_agentaccountinfo;
import com.xjprojectc.uitl.AppContext;
import com.xjprojectc.uitl.ClientMacAddr;
import com.xjprojectc.uitl.Page;
import com.xjprojectc.uitl.PropertyReader;

@SuppressWarnings("serial")
public class SysBaseAction extends BaseAction implements ServletRequestAware {
	@SuppressWarnings("unchecked")
	protected Map session;

	protected int currentPage;
	protected int totalPage;
	protected int totalCount;
	protected int pageSize = AppContext.PAGE_SIZE;

	protected File upfile; // 上传的文件
	protected String upfileContentType;// 文件类型
	protected String upfileFileName;// 上传文件的原始名称
	protected String savePath;// 文件在服务器上的保持路径
	protected int file_type; // 设置文件类型 1图片 0 文件
	protected String name;

	/**
	 * @param currentPage
	 *            the currentPage to set
	 */
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	/**
	 * @return the pageSize
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * @param pageSize
	 *            the pageSize to set
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public File getUpfile() {
		return upfile;
	}

	public void setUpfile(File upfile) {
		this.upfile = upfile;
	}

	public String getUpfileContentType() {
		return upfileContentType;
	}

	public void setUpfileContentType(String upfileContentType) {
		this.upfileContentType = upfileContentType;
	}

	public String getUpfileFileName() {
		return upfileFileName;
	}

	public void setUpfileFileName(String upfileFileName) {
		this.upfileFileName = upfileFileName;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getFile_type() {
		return file_type;
	}

	public void setFile_type(int file_type) {
		this.file_type = file_type;
	}

	public void setPageInfo(Page page) {
		this.currentPage = page.getCurrentPage();
		this.totalPage = page.getTotalPages();
		this.totalCount = page.getTotalRows();
		this.pageSize = page.getPageSize();
	}

	public void jsonOut(String result) throws Exception {
		PrintWriter outer = null;
		ActionContext context = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/json;charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("text/html");
		try {
			outer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (outer != null) {
			outer.print(result);
			outer.flush();
			outer.close();
		} else {
			throw new Exception("输出异常");
		}
	}

	/**
	 * 文件上传
	 * 
	 * @return
	 * @throws Exception
	 */
	public void uploadFile() throws Exception {
		String time = System.currentTimeMillis() + "";
		// 获取web应用程序在服务器上的路径需要访问ServletAPI
		ServletContext sctx = ServletActionContext.getServletContext();
		// 取得web应用程序在服务器上的物理路径
		// 如“D:/apache-tomcat-6.0.16/webapps/struts2Demo/fileUpload”
		String savePath = "";
		if (file_type == 1) {
			savePath = PropertyReader.getValue("/properties.properties",
					"uploadFilePath_image");
		} else {
			savePath = PropertyReader.getValue("/properties.properties",
					"uploadFilePath_file");
		}
		File saveDirectory = new File(savePath);
		// 如果不存在则创建
		if (!saveDirectory.exists()) {
			saveDirectory.mkdirs();
		}
		// 保存文件
		this.name = java.util.UUID.randomUUID().toString().replaceAll("-", "")
				+ upfileFileName.substring(upfileFileName.lastIndexOf("."),
						upfileFileName.length());
		saveFile(new File(savePath + this.name));
		System.out.println(this.name);
		System.out.println(name);
	}

	/**
	 * 保存文件
	 * 
	 */
	private void saveFile(File outputFile) {
		if (this.upfile != null) {
			try {
				FileOutputStream fos = new FileOutputStream(outputFile);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				FileInputStream fis = new FileInputStream(this.upfile);
				BufferedInputStream bis = new BufferedInputStream(fis);
				byte[] buffer = new byte[2048];
				int length = -1;
				while ((length = fis.read(buffer)) != -1) {
					bos.write(buffer, 0, length);
				}
				bos.close();
				fos.close();
				bis.close();
				fis.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	// 图片输出
	public void imgOut(String imgPath) {
		FileInputStream in = null;
		try {
			in = new FileInputStream(new File(imgPath));
			byte[] bt = FileCopyUtils.copyToByteArray(in);
			if (bt != null && bt.length > 0) {
				ActionContext context = ActionContext.getContext();
				HttpServletResponse response = (HttpServletResponse) context
						.get(ServletActionContext.HTTP_RESPONSE);
				response.setContentType("image/jpg");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + imgPath);
				response.getOutputStream().write(bt, 0, bt.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public HttpServletRequest getReqeust(){
		if(this.request == null){
			this.request  =   ServletActionContext.getRequest();
		}
		return this.request;
	}
	
	public HttpServletResponse getResponse(){
		if(this.response == null){
			this.response  =   ServletActionContext.getResponse();
		}
		return this.response;
	}
	
	
	public T_agentaccountinfo getSysUser(){
		return (T_agentaccountinfo) this.getReqeust().getSession().getAttribute("sysUser");
	}
	
	public String getLogid(T_agentaccountinfo agent){
		Random rdm=new Random();
		StringBuffer sb = new StringBuffer();
		sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		sb.append(rdm.nextInt(90)+10);
		sb.append(agent.getUsername());
		return sb.toString();
	} 
	
	public String getClientIP() {  
		if (this.getReqeust().getHeader("x-forwarded-for") == null) {  
			return request.getRemoteAddr();   }  
		return request.getHeader("x-forwarded-for"); 
	} 
	public String getClientMac() {
		/**
		String sip = this.getReqeust().getHeader("x-forwarded-for");
		if (sip == null || sip.length() == 0
				|| "unknown".equalsIgnoreCase(sip)) {
			sip = request.getHeader("Proxy-Client-IP");
		}
		if (sip == null || sip.length() == 0
				|| "unknown".equalsIgnoreCase(sip)) {
			sip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (sip == null || sip.length() == 0
				|| "unknown".equalsIgnoreCase(sip)) {
			sip = request.getRemoteAddr();
		}
		try {
			ClientMacAddr umac = new ClientMacAddr(sip);
			return umac.GetRemoteMacAddr();
		} catch (Exception e) {
			return java.util.UUID.randomUUID().toString().replaceAll("-", "");
		}
		*/
		return "";
	}
	@SuppressWarnings("unchecked")
	public void setSession(Map arg0) {
		this.session = session;
	}

}
